package cn.car.biz.impl;

import cn.car.biz.CameraBiz;
import cn.car.domains.entity.CameraInfoEntity;
import cn.car.domains.vo.camera.CameraRes;
import cn.car.domains.vo.camera.CreateCameraReq;
import cn.car.domains.vo.camera.UpdateCameraReq;
import cn.car.exception.CarAccessControlException;
import cn.car.service.CameraService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class CameraBizImpl implements CameraBiz {

    @Resource
    private CameraService cameraService;

    /**
     * 创建相机
     * 将前端传入的CreateCameraReq转换为Entity并调用服务层保存
     */
    @Override
    public void createCamera(CreateCameraReq req) {
        // VO转换为Entity
        CameraInfoEntity cameraEntity = new CameraInfoEntity();
        BeanUtils.copyProperties(req, cameraEntity);


        // 调用服务层保存相机
        cameraService.addCamera(cameraEntity);
    }

    /**
     * 根据ID获取相机信息
     * 从服务层获取Entity后转换为响应VO
     */
    @Override
    public CameraRes getCameraById(Long id) {
        // 调用服务层查询
        CameraInfoEntity cameraEntity = cameraService.getCameraById(id);
        if (cameraEntity == null) {
            return null;
        }

        // Entity转换为响应VO
        CameraRes cameraRes = new CameraRes();
        BeanUtils.copyProperties(cameraEntity, cameraRes);
        return cameraRes;
    }

    /**
     * 更新相机信息
     */
    @Override
    public void updateCamera(UpdateCameraReq req) {
        // 检查相机是否存在
        CameraInfoEntity existingCamera = cameraService.getCameraById(req.getId());
        if (existingCamera == null) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("相机不存在");
        }

        // VO转换为Entity（只复制需要更新的字段）
        CameraInfoEntity updateEntity = new CameraInfoEntity();
        BeanUtils.copyProperties(req, updateEntity);

        // 调用服务层更新
        cameraService.updateCamera(updateEntity);
    }

    /**
     * 删除相机
     */
    @Override
    public void deleteCamera(Long id) {
        // 检查相机是否存在
        CameraInfoEntity existingCamera = cameraService.getCameraById(id);
        if (existingCamera == null) {
            throw CarAccessControlException.DATE_NOT_EXIST.newInstance("相机不存在");
        }

        // 调用服务层删除
        cameraService.deleteCamera(id);
    }
}
